package com.swu.pad.assignment.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.swu.pad.activity.dao.ActivityDao;
import com.swu.pad.activity.dao.ActivityGroupVisionDao;
import com.swu.pad.activity.entity.Activity;
import com.swu.pad.activity.service.ActivityService;
import com.swu.pad.assignment.dao.AsmtDocumentTptItemDao;
import com.swu.pad.assignment.dao.AssignmentDao;
import com.swu.pad.assignment.dao.AssignmentDocumentTptDao;
import com.swu.pad.assignment.dao.AssignmentPadDao;
import com.swu.pad.assignment.dao.AssignmentScoreDao;
import com.swu.pad.assignment.entity.AsmtDocumentTptItem;
import com.swu.pad.assignment.entity.Assignment;
import com.swu.pad.assignment.entity.AssignmentDocumentTpt;
import com.swu.pad.assignment.entity.AssignmentPad;
import com.swu.pad.assignment.service.AssignmentPadService;
import com.swu.pad.assignment.service.AssignmentService;
import com.swu.pad.comment.dao.CommentDao;
import com.swu.pad.comment.dao.CommentQuestionDao;
import com.swu.pad.comment.entity.CommentQuestion;
import com.swu.pad.course.dao.CourseGroupUserDao;
import com.swu.pad.course.dao.GroupDao;
import com.swu.pad.course.entity.CourseGroupUser;
import com.swu.pad.course.entity.Group;
import com.swu.pad.reflection.dao.RftDimTipsDao;
import com.swu.pad.reflection.dao.RftDimTipsDao;
import com.swu.pad.reflection.entity.RftDimTips;
import com.swu.pad.reflection.entity.RftFeedbackItem;
import com.swu.pad.util.EPLiteClient.EPLiteClient;

@Service
@Transactional
public class AssignmentServiceImpl implements AssignmentService {

	@Autowired
	private GroupDao groupDao;
	@Autowired
	private CommentDao commentDao;
	@Autowired
	private ActivityDao activityDao;
	@Autowired
	private ActivityGroupVisionDao activityGroupVisionDao;
	@Autowired
	private AssignmentDao assignmentDao;
	@Autowired
	private AssignmentPadDao assignmentPadDao;
	@Autowired
	private AssignmentScoreDao assignmentScoreDao;
	@Autowired
	private CourseGroupUserDao courseGroupUserDao;
	@Autowired
	private ActivityService activityService;
	@Autowired
	private AssignmentPadService assignmentPadService;
	@Autowired
	private CommentQuestionDao commentQuestionDao;
	@Autowired
	private EPLiteClient epliteClient;
	@Autowired
	private RftDimTipsDao rftDimTipsDao;
	@Autowired
	private AssignmentDocumentTptDao asmtDTptDao;
	@Autowired
	private AsmtDocumentTptItemDao asmtDTptItemDao;

	public Assignment addAssignment(Assignment assignment) {
		assignment = assignmentDao.saveAndFlush(assignment);
		List<Group> groupList = null;
		if (Assignment.TYPE_SINGLE.equals(assignment.getAssignmentType())) {
			groupList = groupDao.findGroupByCourseIdAndGroupType(assignment.getCourseId(), Group.TYPE_SINGLE);
		} else {
			groupList = groupDao.findGroupByCourseIdAndGroupType(assignment.getCourseId(), Group.TYPE_GROUP);
		}
		
		  for (int i = 0; i < groupList.size(); i++) {
		  assignmentPadService.addAssignmentPad(assignment,groupList.get(i)); 		  
		  }
		 
		return assignment;
	}

	public Assignment updateAssignment(Assignment assignment) {
		List<CommentQuestion> questionList = commentQuestionDao.findByTemplateId(assignment.getReplyTemplateId());
		Map<String, Object> templateMap = new HashMap<String, Object>();
		List<Map<String, String>> multipleList = new ArrayList<Map<String, String>>();
		List<Map<String, String>> singleList = new ArrayList<Map<String, String>>();

		if (questionList != null && questionList.size() > 0) {
			int max = 0;
			for (int i = 0; i < questionList.size(); i++) {
				if (Integer.parseInt(questionList.get(i).getSid()) >= max) {
					max = Integer.parseInt(questionList.get(i).getSid());
				}
			} // 知道了最大的下标
			for (int i = 0; i < max; i++) {
				Map<String, String> questionMap = new HashMap<String, String>();
				int count = 1;
				String score = "";
				for (int j = 0; j < questionList.size(); j++) {
					if (questionList.get(j).getSid().equals(Integer.toString(i + 1))) {
						questionMap.put(questionList.get(j).getId(), questionList.get(j).getQuestion());
						score = questionList.get(j).getScore();
						count++;
					}
				}
				if (!score.equals("")) {// 说明sid不是空
					questionMap.put("score", score);
					if (count > 2) {
						multipleList.add(questionMap);
					} else {
						singleList.add(questionMap);
					}
				}
			}
		}
		templateMap.put("multipleList", multipleList);
		templateMap.put("singleList", singleList);
		//System.out.println(templateMap.toString());

		// z e

		Assignment oldAssignment = assignmentDao.findOne(assignment.getId());
		//在前端 修改了 
		if (!oldAssignment.getAssignmentType().equals(assignment.getAssignmentType())) {
			List<AssignmentPad> assignmentPadList = assignmentPadDao.findAssignmentPadByAssignmentId(oldAssignment.getId());
			for (int i = 0; i < assignmentPadList.size(); i++) {
				assignmentScoreDao.deleteByAssignmentPadId(assignmentPadList.get(i).getId());
				commentDao.deleteByAssignmentPadId(assignmentPadList.get(i).getId());
				epliteClient.deletePad(assignmentPadList.get(i).getId());
				assignmentPadDao.delete(assignmentPadList.get(i));
			}
			List<Group> groupList = null;
			if (Assignment.TYPE_SINGLE.equals(assignment.getAssignmentType())) {
				groupList = groupDao.findGroupByCourseIdAndGroupType(assignment.getCourseId(), Group.TYPE_SINGLE);
			} else {
				groupList = groupDao.findGroupByCourseIdAndGroupType(assignment.getCourseId(), Group.TYPE_GROUP);
			}
			for (int i = 0; i < groupList.size(); i++) {
				Group group = groupList.get(i);
				AssignmentPad assignmentPad = new AssignmentPad();
				assignmentPad.setAssignmentId(assignment.getId());
				assignmentPad.setAssignmentName(assignment.getAssignmentName());
				assignmentPad.setCreateTime(new Date());
				assignmentPad.setGroupId(group.getId());
				assignmentPad.setGroupName(group.getGroupName());
				Map<?, ?> map = epliteClient.createGroupPad(assignmentPad.getGroupId(), assignmentPad.getAssignmentName(), assignment.getAssignmentContent());
				epliteClient.setPublicStatus(map.get("padID").toString(), true);
				assignmentPad.setId(map.get("padID").toString());
				assignmentPadDao.saveAndFlush(assignmentPad);

			}
		}//为什么没有else分支
		if (!oldAssignment.getAssignmentContent().equals(assignment.getAssignmentContent())) {
			List<Group> groupList = null;
			if (Assignment.TYPE_SINGLE.equals(assignment.getAssignmentType())) {
				groupList = groupDao.findGroupByCourseIdAndGroupType(assignment.getCourseId(), Group.TYPE_SINGLE);
			} else {
				groupList = groupDao.findGroupByCourseIdAndGroupType(assignment.getCourseId(), Group.TYPE_GROUP);
			}
			for (int i = 0; i < groupList.size(); i++) {
				AssignmentPad assignmentPad = assignmentPadDao.findAssignmentPadByAssignmentIdAndGroupId(oldAssignment.getId(), groupList.get(i).getId());
				epliteClient.setText(assignmentPad.getId(), assignment.getAssignmentContent());

			}
		}//为什么没有后else分支？？？

		// zdb s

		List<Group> groupList = null;
		if (Assignment.TYPE_SINGLE.equals(assignment.getAssignmentType())) {
			groupList = groupDao.findGroupByCourseIdAndGroupType(assignment.getCourseId(), Group.TYPE_SINGLE);
		} else {
			groupList = groupDao.findGroupByCourseIdAndGroupType(assignment.getCourseId(), Group.TYPE_GROUP);
		}

		for (int i = 0; i < groupList.size(); i++) {

			if (!templateMap.isEmpty()) {
				templateMap.put("assignmentId", assignment.getId());
				//find 前应该先更新    assignment 内容
				AssignmentPad assignmentPad = assignmentPadDao.findAssignmentPadByAssignmentIdAndGroupId(assignment.getId(), groupList.get(i).getId());
				epliteClient.createCommentTemplate(assignmentPad.getId(), templateMap);
			}
		}

		// zdb e
  
		assignmentDao.saveAndFlush(assignment);
		return assignment;
	}

	@Transactional(rollbackFor = Exception.class)
	public void deleteAssignment(String assignmentId) {
		// 删除作业，同时删除assignmentPad(etherpad中的pad),assignmentScore,comment activity,activityGroupVision
		List<AssignmentPad> assignmentPadList = assignmentPadDao.findAssignmentPadByAssignmentId(assignmentId);
		for (int i = 0; i < assignmentPadList.size(); i++) {
			assignmentScoreDao.deleteByAssignmentPadId(assignmentPadList.get(i).getId());
			commentDao.deleteByAssignmentPadId(assignmentPadList.get(i).getId());
			epliteClient.deletePad(assignmentPadList.get(i).getId());
			assignmentPadDao.delete(assignmentPadList.get(i));
		}
		List<Activity> activityList = activityDao.findActivityByAssignmentId(assignmentId);
		for (int i = 0; i < activityList.size(); i++) {
			activityGroupVisionDao.deleteByActivityId(activityList.get(i).getId());
			activityDao.delete(activityList.get(i));
		}
		assignmentDao.delete(assignmentId);
	}

	public List<Assignment> getAssignmentByCourseId(String courseId) {
		return assignmentDao.findAssignmentByCourseId(courseId);
	}

	public Assignment getAssignment(String assignmentId) {
		return assignmentDao.findOne(assignmentId);
	}

	public Map<String, Object> getAssignmentDetail(String assignmentId) {
		// {assignment:{},assignmentPad:[]}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("assignment", assignmentDao.findOne(assignmentId));
		map.put("assignmentPad", assignmentPadDao.findAssignmentPadByAssignmentId(assignmentId));
		return map;
	}

	public AssignmentPad getUserAssignmentPad(String assignmentId, String groupId) {
		AssignmentPad assignmentPad = assignmentPadDao.findAssignmentPadByAssignmentIdAndGroupId(assignmentId, groupId);
		return assignmentPad;
	}

	public CourseGroupUser getUserAssignmentSession(String assignmentId, String userId) {
		Assignment assignment = assignmentDao.findOne(assignmentId);
		CourseGroupUser courseGroupUser = null;
		if (Assignment.TYPE_SINGLE.equals(assignment.getAssignmentType())) {
			courseGroupUser = courseGroupUserDao.findCourseGroupUserByCourseIdAndUserIdAndGroupType(assignment.getCourseId(), userId, Group.TYPE_SINGLE);
		} else {
			courseGroupUser = courseGroupUserDao.findCourseGroupUserByCourseIdAndUserIdAndGroupType(assignment.getCourseId(), userId, Group.TYPE_GROUP);
		}
		return courseGroupUser;
	}

	public String getAssignmentPadCurrentId(String assignmentId, String groupId) {
		AssignmentPad assignmentPad = assignmentPadDao.findAssignmentPadByAssignmentIdAndGroupId(assignmentId, groupId);
		return assignmentPad != null ? assignmentPad.getId() : "";
	}

	public Map<String, Object> getCommentAssignmentPad(String activityId, String userId) {
		return activityService.getCommentAssignmentPad(activityId, userId);
	}

	@Override
	public boolean hasGroupAssignment(String courseId) {
		List<Assignment> assignmentList = assignmentDao.findAssignmentByCourseIdAndAssignmentType(courseId, Assignment.TYPE_GROUP);
		if (assignmentList != null && assignmentList.size() > 0)
			return true;
		return false;
	}

	@Override
	public boolean hasSingleAssignment(String courseId) {
		List<Assignment> assignmentList = assignmentDao.findAssignmentByCourseIdAndAssignmentType(courseId, Assignment.TYPE_SINGLE);
		if (assignmentList != null && assignmentList.size() > 0)
			return true;
		return false;
	}

	@Override
	public List<Group> getAssignmentGroup(String assignmentId) {
		Assignment assignment = assignmentDao.getOne(assignmentId);
		if(assignment==null){
			return null;
		}
		List<Group> groupList = groupDao.findGroupByCourseIdAndGroupTypeOrderByGroupNumAsc(assignment.getCourseId(), assignment.getAssignmentType());
		return groupList;
	}

	@Override
	public void replacePad(String assignmentId, String groupId) {
		Assignment assignment = assignmentDao.getOne(assignmentId);
		if(assignment==null)
			return;
		// 删除重新创建新pad
		epliteClient.deletePad(groupId+"$"+assignment.getAssignmentName());
		Map map = epliteClient.createGroupPad(groupId, assignment.getAssignmentName(),assignment.getAssignmentContent());
		epliteClient.setPublicStatus(groupId+"$"+assignment.getAssignmentName(), true);
		// 更新评论模板
		updateTemplate(assignmentId,groupId+"$"+assignment.getAssignmentName(),assignment.getReplyTemplateId());
		
	}
	
	public void updateTemplate(String assignmentId,String padId, String replyTemplateId){
		List<CommentQuestion> questionList = commentQuestionDao.findByTemplateId(replyTemplateId);
		Map<String, Object> templateMap = new HashMap<String, Object>();
		List<Map<String, String>> multipleList = new ArrayList<Map<String, String>>();
		List<Map<String, String>> singleList = new ArrayList<Map<String, String>>();

		if (questionList != null && questionList.size() > 0) {
			int max = 0;
			for (int i = 0; i < questionList.size(); i++) {
				if (Integer.parseInt(questionList.get(i).getSid()) >= max) {
					max = Integer.parseInt(questionList.get(i).getSid());
				}
			} // 知道了最大的下标
			for (int i = 0; i < max; i++) {
				Map<String, String> questionMap = new HashMap<String, String>();
				int count = 1;
				String score = "";
				for (int j = 0; j < questionList.size(); j++) {
					if (questionList.get(j).getSid().equals(Integer.toString(i + 1))) {
						questionMap.put(questionList.get(j).getId(), questionList.get(j).getQuestion());
						score = questionList.get(j).getScore();
						count++;
					}
				}
				if (!score.equals("")) {// 说明sid不是空
					questionMap.put("score", score);
					if (count > 2) {
						multipleList.add(questionMap);
					} else {
						singleList.add(questionMap);
					}
				}
			}
		}
		templateMap.put("multipleList", multipleList);
		templateMap.put("singleList", singleList);

		if (!templateMap.isEmpty()) {
			templateMap.put("assignmentId", assignmentId);
			epliteClient.createCommentTemplate(padId, templateMap);
		}
	}
   
	//创建作业目录
	@Override
	public void saveAsmtDocumentTpt(AssignmentDocumentTpt asmtDocumentTpt) {
		asmtDTptDao.saveAndFlush(asmtDocumentTpt);
	}
    //获取所有作业文档目录
	@Override
	public List<AssignmentDocumentTpt> getAsmtDocumentTpts() {
		return asmtDTptDao.findAll();
	}
    
	//删除一个作业目录
	@Override
	public void deleteAsmtDocumentTpt(String templateId) {
		asmtDTptDao.delete(templateId);
		List<AsmtDocumentTptItem> asmtDTptItems=asmtDTptItemDao.findByTemplateId(templateId);
		 for (int i = 0; i < asmtDTptItems.size(); i++) {
			 asmtDTptItemDao.delete(asmtDTptItems.get(i));//删除模板关联  条目
		}
		
	}
    
	//保存一个文档
	@Override
	public void saveAsmtDocumentTptItem(AsmtDocumentTptItem asmtDocumentTptItem) {
		asmtDTptItemDao.saveAndFlush(asmtDocumentTptItem);
	}
   //获取 目录 所有文档条目
	@Override
	public List<AsmtDocumentTptItem> getAsmtDocumentTptItems(String templateId) {
		return asmtDTptItemDao.findByTemplateId(templateId);
	}
   //删除一个条目
	@Override
	public void deleteAsmtDocumentTptItem(String itemId) {
		asmtDTptItemDao.delete(itemId);
	} 
	
    //根据作业id 获取作业关联文档
	@Override
	public List<AsmtDocumentTptItem> getAsmtDocuments(String assignmentId) {
		Assignment assignment=assignmentDao.findOne(assignmentId);
		String asmtDocumentTptID=assignment.getAsmtDocumentTptId();
		return asmtDTptItemDao.findByTemplateId(asmtDocumentTptID);
	}

}
